package uestc.lj.gulishop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import uestc.lj.common.utils.PageUtils;
import uestc.lj.common.utils.Query;
import uestc.lj.gulishop.product.dao.BrandDao;
import uestc.lj.gulishop.product.entity.BrandEntity;
import uestc.lj.gulishop.product.service.BrandService;
import uestc.lj.gulishop.product.service.CategoryBrandRelationService;

import java.util.List;
import java.util.Map;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // 实现查询功能
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            wrapper.eq("brand_id", key).or().like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 同步更新数据表及其冗余的中间表
     *
     * @param brand
     */
    @Override
    @Transactional
    public void updateByIdDetail(BrandEntity brand) {
        // 1.更新自己表中的数据
        this.updateById(brand);
        // 2.更新关联中间表中的数据
        if (!StringUtils.isEmpty(brand.getName())) {
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
            // TODO 更新其他关联中间表
        }
    }

    /**
     * 根据品牌Id集合查询所有品牌的信息
     *
     * @param brandIds
     * @return
     */
    @Override
    public List<BrandEntity> getBrandsByIds(List<Long> brandIds) {
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        wrapper.in("brand_id", brandIds);
        return baseMapper.selectList(wrapper);
    }

}